package com.jht.bletool.fragment;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.toast.ToastUtils;
import com.jht.bletool.R;
import com.jht.bletool.adapter.BlePrintLogAdapter;
import com.jht.bletool.entity.DataLog;
import com.suke.widget.SwitchButton;

import java.util.Objects;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BleLogFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BleLogFragment extends Fragment {
    private static final String TAG = "BleLogFragment";
    private BluetoothDevice bluetoothDevice;
    private LinearLayout mIvEmptyView;
    private RecyclerView mRvPrintLog;
    private BlePrintLogAdapter blePrintLogAdapter;
    private LinearLayout mLlRvParent;
    private SwitchButton mSwitchButton;
    private long currentTime = 0;
    private boolean isRecordTime = false; //是否记录过时间
    private boolean pause = false; //是否fragment暂停
    private DataLogReceiver dataLogReceiver = new DataLogReceiver();
    public BleLogFragment(BluetoothDevice ble_device) {
        bluetoothDevice = ble_device;
    }

    public static BleLogFragment newInstance(BluetoothDevice ble_device) {
        return new BleLogFragment(ble_device);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FragmentActivity activity = getActivity();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("send_log");
        Objects.requireNonNull(activity).registerReceiver(dataLogReceiver, intentFilter);
        Log.i(TAG, "onCreate: registerReceiver");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ble_data_log, container, false);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRvPrintLog = view.findViewById(R.id.rv_print_log);
        mSwitchButton = view.findViewById(R.id.switch_button);
        mRvPrintLog.setOnTouchListener(new View.OnTouchListener() {
            float lastY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastY = event.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        if (event.getY() - lastY > 0) {
                            mSwitchButton.setChecked(false);
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

        mIvEmptyView = view.findViewById(R.id.iv_empty_view);
        mLlRvParent = view.findViewById(R.id.ll_rv_parent);

        mSwitchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            /**
             *
             * @param view 表示SwitchButton
             * @param isChecked 代表当前按钮的 check 状态
             */
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (!isChecked) {
                    isRecordTime = true;
                    currentTime = System.currentTimeMillis();
                }
            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false);
        mRvPrintLog.setLayoutManager(linearLayoutManager);
        blePrintLogAdapter = new BlePrintLogAdapter(getActivity());
        mRvPrintLog.setAdapter(blePrintLogAdapter);

    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e(TAG, "onPause: 日志暂停");
        if (mSwitchButton.isChecked()) {
            isRecordTime = true;
            currentTime = System.currentTimeMillis();
        }
        pause = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume: 日志继续");
        pause = false;
    }

    private void updateLog(DataLog dataLog) {
        mIvEmptyView.setVisibility(View.GONE);
        mRvPrintLog.setVisibility(View.VISIBLE);
        mLlRvParent.setVisibility(View.VISIBLE);
        Log.e(TAG, "updateLog: ================");
        blePrintLogAdapter.addData(dataLog);
        // 自动滚动 需要被控制
        if (mSwitchButton.isChecked()) {
            if (pause) {
                return;
            }
            if (isRecordTime) { //表示之前记录过时间，则可以不采用平滑滚动
                long temp = System.currentTimeMillis();
                if (temp - currentTime > 15 * 1000) {
                    mRvPrintLog.scrollToPosition(blePrintLogAdapter.getItemCount() - 1);
                } else {
                    mRvPrintLog.smoothScrollToPosition(blePrintLogAdapter.getItemCount() - 1);
                }
                isRecordTime = false;
            } else {
                mRvPrintLog.smoothScrollToPosition(blePrintLogAdapter.getItemCount() - 1);
            }

        }
    }

    public void clearAllLog() {
        blePrintLogAdapter.clear();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Objects.requireNonNull(getActivity()).unregisterReceiver(dataLogReceiver);
    }

    private class DataLogReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if ("send_log".equals(intent.getAction())) {
                DataLog dataLog = (DataLog) intent.getParcelableExtra("ble_log");
                boolean ble_close = intent.getBooleanExtra("ble_close", false);
                updateLog(dataLog);
                if (ble_close) {
                    ToastUtils.show("设备断开了，请重新连接！");
                    Objects.requireNonNull(getActivity()).finish();
                }
            }
        }
    }

}